<template>
  <div
    class="card border-base-card after:rounded-md m-1 rounded-md pt-3 px-5 pb-5 text-text-01 black:text-text-01-dark bg-background-01 black:bg-background-01-dark inline-block absolute hover:shadow-selectSection hover:z-10 hover:after:border-border-06 hover:after:border-2 black:hover:after:border-border-06-dark"
    v-loading="loading"
    @click="selectSection(section)"
    :class="{
      'after:!border-border-04 after:!border black:after:!border-border-04-dark shadow-selectSection':
        active
    }"
    ref="cardEl"
    :style="{ width: renderHandler?.fullWidth.value ? 'calc(100% - 8px)' : 'calc(50% - 8px)' }"
    v-track:click="{
      id: 'thspc_f10_copilot_card',
      logmap: () => ({ type: section.pid, sid: section.id })
    }"
    @mouseover="recommendQuestion('in')"
    @mouseleave="recommendQuestion('out')"
  >
    <div class="text-base font-semibold flex justify-start items-center gap-2">
      <span class="w-1 h-4 bg-title-bar"></span>
      <span class="flex-1 truncate">{{ section.title }}</span>
    </div>
    <el-radio-group
      v-model="activeTabIndex"
      size="small"
      v-if="section.view_wrapper.views.length > 1"
      @change="changeViewIndex"
    >
      <el-radio-button
        v-for="(view, index) in section.view_wrapper.views"
        :key="view.name"
        :label="view.name"
        :value="index"
      />
    </el-radio-group>
    <div
      ref="chartContent"
      @click="stopPropagation"
      v-show="renderHandler?.isDataValid()"
      class="h-[212px] mt-3"
      :class="{ 'h-auto': renderHandler?.fitHeight.value }"
    ></div>
    <div
      v-show="!renderHandler?.isDataValid()"
      class="h-[212px] mt-3 flex justify-center items-center flex-col gap-4"
    >
      <img src="../../../assets/nodata.png" class="h-[60px]" alt="" srcset="" />
      <span class="text-xs text-text-03 black:text-text-03-dark"
        >该股暂无【{{ section.title }}】的相关数据</span
      >
    </div>
  </div>
</template>
<script setup lang="ts">
import type { Section } from '@/common/models/recommend-result'
import { useComponentRender, type ComponentRenderReturn } from '../services/component-render'
import { onBeforeUnmount, onMounted, nextTick, ref, type Ref, computed, watch } from 'vue'
import { usePanelStore } from '@/stores/panel'
import { getEventBus } from '@/common/services/chat-event-bus'
import { useAppInfoStore } from '@/stores/app'

const props = defineProps<{
  section: Section
}>()

const activeTabIndex = ref(props.section.view_index < 0 ? 0 : props.section.view_index)

const chartContent = ref<HTMLElement | null>(null)

const cardEl = ref<HTMLElement | null>(null)

const loading = ref(false)

const panelStore = usePanelStore()

const appStore = useAppInfoStore()

const skin = computed(() => appStore.skin)

const active = computed(() => panelStore.selectSection?.id === props.section.id)

const {
  sectionSelectEventBus,
  updateViewEventBus,
  sectionOperatorEventBus,
  robotQuestionEventBus,
  insightConfigEventBus
} = getEventBus()

let renderHandler: ComponentRenderReturn | null = null

const cardHoverTimer: Ref<any> = ref(null)

onMounted(async () => {
  loading.value = true
  renderHandler = useComponentRender(chartContent.value!, props.section, 'long-small', 'page')
  console.log(renderHandler)
  await nextTick()
  renderHandler.renderChart()
  await nextTick()
  loading.value = false
  setTimeout(() => {
    updateViewEventBus.emit({ id: 'updateView' })
  })
})

watch(props.section, () => renderHandler?.renderChart(), { deep: true })

watch(skin, () => {
  renderHandler?.renderChart()
  setTimeout(() => {
    updateViewEventBus.emit({ id: 'updateView' })
  })
})

const sectionOperatorHandler = ({ id, section }: { id: string; section: Section | null }) => {
  if (section?.id === props.section.id) {
    if (id === 'card_change') {
      renderHandler?.changeChart({ pid: section.pid })
    }
    if (id === 'close_insight' && section) {
      renderHandler?.closeInsight()
    }
  }
}

function changeViewIndex(index: number) {
  renderHandler?.changeViewIndex(index)
  setTimeout(() => {
    updateViewEventBus.emit({ id: 'updateView' })
  })
}

onBeforeUnmount(() => {
  console.log('destory component')
  renderHandler?.destoryChart?.()
  sectionOperatorEventBus.off(sectionOperatorHandler)
})

const selectSection = (section: Section) => {
  console.log(renderHandler, renderHandler?.getCommands)
  sectionSelectEventBus.emit({ section, commands: renderHandler!.commondsParam.value })
}

function stopPropagation(e: MouseEvent) {
  if (renderHandler?.emitCustomEvent.value) {
    e.stopPropagation()
  }
}

function recommendQuestion(type: string) {
  console.log('mouse event', type)
  if (type === 'in') {
    if (cardHoverTimer.value) return
    cardHoverTimer.value = setTimeout(() => {
      robotQuestionEventBus.emit({ section: props.section })
    }, 5000)
  } else {
    clearTimeout(cardHoverTimer.value)
    cardHoverTimer.value = null
  }
}

sectionOperatorEventBus.on(sectionOperatorHandler)

insightConfigEventBus.on((insightConfig) => {
  if (insightConfig.param.sid === props.section.id) {
    renderHandler?.renderInsight(insightConfig)
  }
})

defineExpose({
  selectSection
})
</script>
